package com.jlastu.androidsx.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.jlastu.androidsx.App;
import com.jlastu.androidsx.R;
import com.jlastu.androidsx.dao.UserDao;
import com.jlastu.androidsx.database.GreenDaoManager;
import com.jlastu.androidsx.databinding.FragmentMeBinding;
import com.jlastu.androidsx.model.MeModel;
import com.jlastu.androidsx.ui.user.ShopAddressListActivity;
import com.jlastu.androidsx.ui.user.UserInfoActivity;
import com.jlastu.androidsx.ui.user.XuetangListActivity;
import com.jlastu.androidsx.widget.MenuOptionsView;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.huantansheng.easyphotos.utils.permission.PermissionUtil;
import com.kongzue.dialogx.dialogs.InputDialog;
import com.kongzue.dialogx.interfaces.OnInputDialogButtonClickListener;

import java.util.ArrayList;

import cn.project.base.baseui.BaseNormalFragment;

public class UserMeFragment extends BaseNormalFragment<FragmentMeBinding> {


    MeModel meModel;
    UserDao userDao;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_me;
    }



    @Override
    protected void initData() {
        userDao = GreenDaoManager.getmInstance().getDaoSession().getUserDao();
        meModel = new ViewModelProvider(getActivity()).get(MeModel.class);
        if (App.getInstance().user!=null){
            mBinding.tvName.setText(App.getInstance().user.getName());
            if (!TextUtils.isEmpty(App.getInstance().user.getHead_url())){
                Glide.with(getActivity()).load(App.getInstance().user.getHead_url()).into(mBinding.imageHead);
            }
        }
        mBinding.icXuetang.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                startActivity(new Intent(getActivity(), XuetangListActivity.class));
            }
        });


        mBinding.icUser.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                startActivity(new Intent(getActivity(), UserInfoActivity.class));
            }
        });
        mBinding.icSettingAddress.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                startActivity(new Intent(getActivity(), ShopAddressListActivity.class));
            }
        });
        mBinding.icSettingOrder.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                startActivity(new Intent(getActivity(), OrderListActivity.class));
            }
        });

        mBinding.icChangePassword.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                new InputDialog("修改密码", "", "确定", "取消", "")
                        .setCancelable(false)
                        .setTitleIcon(R.mipmap.logo)
                        .setInputHintText("输入新密码")
                        .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                            @Override
                            public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                                App.getInstance().user.setPassword(inputStr);
                                userDao.update(App.getInstance().user);
                                showToast("修改密码成功");

                                return false;
                            }
                        })
                        .show();
            }
        });




        //设置账号
        mBinding.icChangeName.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                new InputDialog("修改账号", "", "确定", "取消", "")
                        .setCancelable(false)
                        .setTitleIcon(R.mipmap.logo)
                        .setInputHintText("输入账号")
                        .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                            @Override
                            public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                                if (TextUtils.isEmpty(inputStr)){
                                    showToast("输入不能为空");
                                    return false;
                                }
                                App.getInstance().user.setName(inputStr);
                                mBinding.tvName.setText(inputStr);
                                userDao.update(App.getInstance().user);
                                showToast("修改账号成功");
                                return false;
                            }
                        })
                        .show();
            }
        });



        final String[] permissions;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S_V2){
            permissions = new String[]{
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_MEDIA_AUDIO,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.READ_MEDIA_IMAGES};
        }else {
            permissions =new String[]{
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }
        if (PermissionUtil.checkAndRequestPermissionsInActivity(getActivity(),
                permissions)) {
            preLoadAlbums();
        }
        mBinding.imageHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EasyPhotos
                        .createAlbum(getActivity(), true,true, ImageEngine.getInstance())
                        .setCount(1)
                        .setFileProviderAuthority("com.example.shopapp.fileprovider")
                        .start(new SelectCallback() {
                            @Override
                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                //获取file，进行对应操作
                                if (photos.size()>0){
                                    String path =  photos.get(0).path;
                                    Glide.with(getActivity()).load(path).into(mBinding.imageHead);
                                    App.getInstance().user.setHead_url(path);
                                    userDao.update(App.getInstance().user);
                                }
                            }
                            @Override
                            public void onCancel() {

                            }
                        });
            }
        });
        mBinding.btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                meModel.logout();
            }
        });
    }

    /**
     * 预加载相册扫描
     */
    private void preLoadAlbums() {
        EasyPhotos.preLoad(getActivity());
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull final String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        PermissionUtil.onPermissionResult(getActivity(), permissions, grantResults,
                new PermissionUtil.PermissionCallBack() {
                    @Override
                    public void onSuccess() {
                        preLoadAlbums();
                    }

                    @Override
                    public void onShouldShow() {
                    }

                    @Override
                    public void onFailed() {
                    }
                });
    }

}
